package io.quarkus.test.config;

import org.eclipse.microprofile.config.spi.ConfigProviderResolver;
import org.junit.platform.launcher.LauncherSession;
import org.junit.platform.launcher.LauncherSessionListener;

import io.quarkus.runtime.LaunchMode;

/**
 * A JUnit {@link LauncherSessionListener}, used to register the initial test config. Test set up code can safely call
 * <code>ConfigProvider.getConfig()</code> to retrieve an instance of the Quarkus configuration.
 * <p>
 * The test config only contains sources known at bootstrap test time. For instance, config sources generated by
 * Quarkus are not available in the test config.
 */
public class ConfigLauncherSession implements LauncherSessionListener {
    @Override
    public void launcherSessionOpened(final LauncherSession session) {
        // Ideally the classloader would be correct when this is launched,
        // but for gradle, test class loading happens fairly shortly after this is called,
        // before the formal loading phase. To make that work, the TCCL may have been
        // set to the FCL by the time this is called, even though we want config to live on the app classloader
        ClassLoader old = Thread.currentThread().getContextClassLoader();
        Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader());
        try {
            TestConfigProviderResolver resolver = new TestConfigProviderResolver();
            ConfigProviderResolver.setInstance(resolver);
            resolver.getConfig(LaunchMode.TEST);
        } finally {
            Thread.currentThread().setContextClassLoader(old);
        }

    }

    @Override
    public void launcherSessionClosed(final LauncherSession session) {
        try {
            ((TestConfigProviderResolver) ConfigProviderResolver.instance()).restore();
        } catch (ClassCastException e) {
            e.printStackTrace();
            throw new IllegalStateException(
                    "Internal error: Attempted to close a launcher session which had already been closed.");

        }
    }
}
